package com.le.edu.utils;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.le.edu.exception.NeedLoginException;
import com.le.edu.resp.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * hutool生成token
 */
public class JwtUtils {

    private static final String KEY = "just";

    /**
     * 创建token
     *
     * @param id
     * @param username
     * @return
     */
    public static String createToken(Long id, String username) {
        DateTime now = DateTime.now();
        DateTime expTime = now.offsetNew(DateField.HOUR, 5);
        Map<String, Object> payload = new HashMap<>();
        // 签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        // 过期时间
        payload.put(JWTPayload.EXPIRES_AT, expTime);
        // 生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        // 内容
        payload.put("id", id);
        payload.put("username", username);
        return JWTUtil.createToken(payload, KEY.getBytes());
    }

    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public static boolean validate(String token) {
        JWT jwt = JWTUtil.parseToken(token).setKey(KEY.getBytes());
        // validate包含了verify
        boolean validate = jwt.validate(0);
        return validate;
    }

    public static Long getJSONObject(String token) {
        JWT jwt = JWTUtil.parseToken(token).setKey(KEY.getBytes());
        String id = jwt.getPayload("id").toString();
        return Long.valueOf(id);
    }

    public static Long getUserId(HttpServletRequest request) {
        String token = request.getHeader(ConstUtils.TOKEN);
        if (StrUtil.isEmpty(token)) {
            throw new NeedLoginException(ResultCodeEnum.USER_NEED_LOGIN);
        }
        return JwtUtils.getJSONObject(token);
    }


}
